package io.bdmc.common.aspect;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.bdmc.common.annotation.ApiDataFilter;
import io.bdmc.common.exception.RRException;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.MyPage;
import io.bdmc.modules.sys.entity.SysUser;
import io.bdmc.modules.sys.service.SysUserService;

/**
 * 数据过滤，切面处理类
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2017/9/17 15:02
 */
@Aspect
@Component
public class ApiDataFilterAspect {
    @Autowired
    private SysUserService _userSvs;

    @Autowired
    public HttpServletRequest request;

    @Pointcut("@annotation(io.bdmc.common.annotation.ApiDataFilter)")
    public void dataFilterCut() {

    }

    @Before("dataFilterCut()")
    @SuppressWarnings("all")
    public void dataFilter(JoinPoint point) throws Throwable {
        Object params = point.getArgs()[0];
        String openid =  request.getAttribute("loginName").toString();
        SysUser user = _userSvs.queryByOpenid(openid);
        if(params != null && params instanceof Map){
            //如果不是超级管理员，则只能查询本部门及子部门数据
            if(user.getUserId() != Constant.SUPER_ADMIN){
                Map map = (Map)params;
                map.put("filterSql", getFilterSQL(user, point));
            }
            return ;
        }else if(params != null && params instanceof MyPage){
            //如果不是超级管理员，则只能查询本部门及子部门数据
            if(user.getUserId() != Constant.SUPER_ADMIN){
                MyPage mp = (MyPage)params;
                mp.setFilterSql(getFilterSQL(user, point));      
            }
            return;
        }

        throw new RRException("要实现数据权限接口的参数，只能是Map类型，且不能为NULL");
    }

    /**
     * 获取数据过滤的SQL
     */
    private String getFilterSQL(SysUser user, JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        ApiDataFilter dataFilter = signature.getMethod().getAnnotation(ApiDataFilter.class);
        //获取表的别名
        String tableAlias = dataFilter.tableAlias();
        if(StringUtils.isNotBlank(tableAlias)){
            tableAlias +=  ".";
        }
        String str = "("+tableAlias+"dept_id="+user.getDeptId()+" or LOCATE(CONCAT( ',',"+user.getDeptId()+",','), CONCAT(',',"+tableAlias+"cascader,','))>0)";
        return str;
        // //获取子部门ID
        // String subDeptIds = sysDeptService.getSubDeptIdList(user.getDeptId());
        // List<Long> roles = userRoleSvs.queryRoleIdList(user.getUserId());//
        // if(roles.size()>0){
        //     Long roleid = roles.get(0);//获取第一个角色
        //     List<Long> roleDeptIds =  roleDeptSvs.queryDeptIdList(roleid);
        //     for (Long id : roleDeptIds) {
        //         subDeptIds+=","+id;
        //     }
        // }

        // StringBuilder filterSql = new StringBuilder();
        // filterSql.append("and (");
        // filterSql.append(tableAlias).append("dept_id in(").append(subDeptIds).append(")");

        // filterSql.append(")");
        // return filterSql.toString();
    }
}
